﻿package com.taropan.wallpaper.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import com.taropan.wallpaper.CrashApplication;

import android.app.WallpaperManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.GridView;
import android.widget.ListView;

public class Utils {


	public static boolean debugFlag = true;
	
	static long copy(File in, OutputStream out) throws IOException {
		return copy(new FileInputStream(in), out);
	}

	static long copy(InputStream in, File out) throws IOException {
		return copy(in, new FileOutputStream(out));
	}

	static void saveBitmap(Bitmap bitmap, OutputStream out) {
		bitmap.compress(CompressFormat.PNG, 100, out);
	}

	/**
	 * Pipe an InputStream to the given OutputStream
	 * <p />
	 * Taken from Apache Commons IOUtils.
	 * 
	 * @param in
	 * @param out
	 * @throws IOException
	 */
	private static long copy(InputStream input, OutputStream output) throws IOException {
		byte[] buffer = new byte[1024 * 4];
		long count = 0;
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
			count += n;
		}
		return count;
	}


	
	private static final String TAG = Utils.class.getSimpleName();
	
	public static void setListViewHeightBasedOnChildren(ListView listView) {
		Adapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		params.height += 60;
		listView.setLayoutParams(params);
	}
	
	public static boolean isExternalStorageAvilable() {
		String state = Environment.getExternalStorageState();
		if ( Environment.MEDIA_MOUNTED.equals( state ) ) {
			return true;
		}
		return false;
	}
	
	public static String getTime(Date date) {
		TimeZone t = TimeZone.getTimeZone("GMT+08:00");// 获取东8区TimeZone
		Calendar calendar = Calendar.getInstance(t);
		calendar.setTime(date);
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int min = calendar.get(Calendar.MINUTE);
		int ss = calendar.get(Calendar.SECOND);

		String time = year + "-" + (month < 10 ? "0" : "") + month + '-'
				+ (day < 10 ? "0" : "") + day + ' ' + (hour < 10 ? "0" : "")
				+ hour + ':' + (min < 10 ? "0" : "") + min + ":"
				+ (ss < 10 ? "0" : "") + ss;
		return time;
	}

	public static String getDate() {
		TimeZone t = TimeZone.getTimeZone("GMT+08:00");// 获取东8区TimeZone
		Calendar calendar = Calendar.getInstance(t);
		calendar.setTimeInMillis(System.currentTimeMillis());
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		String date = year + "-" + (month < 10 ? "0" : "") + month + '-'
				+ (day < 10 ? "0" : "") + day;
		return date;
	}
	public static void setListViewHeightBasedOnChildren(GridView listView) {
		// 获取GistView对应的Adapter
		Adapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}

		int totalHeight = 0;
		for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0); // 计算子项View 的宽高
			totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight;
		listView.setLayoutParams(params);
	}
	
	/**
	 * 读取输入流数据
	 * @param is
	 * @return
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream is) throws Exception {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		byte[] buffer = new byte[2048];
		int len = 0;
		while ((len = is.read(buffer)) != -1) {
			os.write(buffer, 0, len);
		}
		is.close();
		return os.toByteArray();
	}
	
	public static void dout(String str) {
		if (debugFlag) {
			Log.d("[dout]", "str>>>>>>>>>>" + str);
		}
	}

	public static void dout(String str, String str2) {
		if (debugFlag) {
			Log.d("[dout]", str+">>>>>>>>>>" + " " + str2);
		}
	}

	public static void setWallpaper(String path) {
		CrashApplication app = CrashApplication.getApplication(AppContext.getContext());
		int height = app.CanvasHeight;
		int width = app.CanvasWidth << 1; // best wallpaper width is
														// twice screen width

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path,options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, width, height);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		Bitmap decodedSampleBitmap = BitmapFactory.decodeFile(path, options);

		WallpaperManager wm = WallpaperManager
				.getInstance(AppContext.getContext());
		try {
			wm.setBitmap(decodedSampleBitmap);
		} catch (IOException e) {
			e.printStackTrace();
		}

		// WallpaperManager wallpaperManager =
		// //WallpaperManager.getInstance(this);
		// Bitmap bitmap = //BitmapFactory.decodeResource(getResources(),
		// R.drawable.dashboard);
		// Bitmap useThisBitmap = //Bitmap.createScaledBitmap(bitmap,
		// wallpaperManager.getDesiredMinimumWidth(),
		// wallpaperManager.getDesiredMinimumHeight(), true);
		// bitmap.recycle();

		// try {
		// wallpaperManager.setBitmap//(useThisBitmap);
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		// wm.suggestDesiredDimensions(w, h);
		// Log.e("", "Width : " + //wallpaperManager.getDesiredMinimumWidth());
		// Log.e("", "Height : " +
		// //wallpaperManager.getDesiredMinimumHeight());
		
	}
	
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;
		if (height > reqHeight || width > reqWidth) {
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}
		return inSampleSize;
	}
	
//	private void setWallpaper() {
//	    try {
//	        WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
//	        //import non-scaled bitmap wallpaper
//	        BitmapFactory.Options options = new BitmapFactory.Options();
//	        options.inScaled = false;
//	        Bitmap wallpaper = BitmapFactory.decodeResource(getResources(), R.drawable.wallpaper, options);
//
//	        if (wallpaperManager.getDesiredMinimumWidth() > wallpaper.getWidth() &&
//	                wallpaperManager.getDesiredMinimumHeight() > wallpaper.getHeight()) {
//	            //add padding to wallpaper so background image scales correctly
//	            int xPadding = Math.max(0, wallpaperManager.getDesiredMinimumWidth() - wallpaper.getWidth()) / 2;
//	            int yPadding = Math.max(0, wallpaperManager.getDesiredMinimumHeight() - wallpaper.getHeight()) / 2;
//	            Bitmap paddedWallpaper = Bitmap.createBitmap(wallpaperManager.getDesiredMinimumWidth(), wallpaperManager.getDesiredMinimumHeight(), Bitmap.Config.ARGB_8888);
//	            int[] pixels = new int[wallpaper.getWidth() * wallpaper.getHeight()];
//	            wallpaper.getPixels(pixels, 0, wallpaper.getWidth(), 0, 0, wallpaper.getWidth(), wallpaper.getHeight());
//	            paddedWallpaper.setPixels(pixels, 0, wallpaper.getWidth(), xPadding, yPadding, wallpaper.getWidth(), wallpaper.getHeight());
//
//	            wallpaperManager.setBitmap(paddedWallpaper);
//	        } else {
//	            wallpaperManager.setBitmap(wallpaper);
//	        }
//	    } catch (IOException e) {
//	        Log.e(TAG,"failed to set wallpaper");
//	    }
//	}
	  public static String getVersionName(Context context) {
	        try {

	            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(),
	                    0);
	            return info.versionName;
	        } catch (NameNotFoundException e) {
	            return null;
	        }
	    }

	    public static int getVersionCode(Context context) {
	        try {

	            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(),
	                    0);
	            return info.versionCode;
	        } catch (NameNotFoundException e) {
	            return 0;
	        }
	    }
	    
	    
	    
}
